
import os
import requests
import json


class File:
    # 保存对话到本地文件
    def save_conversation(txt_data,  file_path, role):
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                # 如果文件存在，这里什么都不会发生（或者你可以读取并处理内容）
                pass
        except FileNotFoundError:
            # 如果文件不存在，则创建文件并写入初始内容
            with open(file_path, 'a', encoding='utf-8') as file:
                file.write('[')
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # 删除最后一个字符
        # new_content = content[:-1]
        # # 将修改后的内容写回文件
        # with open(file_path, 'w', encoding='utf-8') as file:
        #     file.write(new_content)
        with open(file_path, 'a', encoding='utf-8') as file:
            if content!='[':
                file.write(',')
            file.write('{"role": "'+role+'","content": "'+txt_data.replace('\n', '\\n')+'"}')
            # file.write(']')


    # 导入历史文件
    def import_history(file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                # 如果文件存在，这里什么都不会发生（或者你可以读取并处理内容）
                pass
        except FileNotFoundError:
            # 如果文件不存在，则创建文件并写入初始内容
            with open(file_path, 'a', encoding='utf-8') as file:
                file.write('[')
        with open(file_path, 'r', encoding='utf-8') as file:
            conversations = file.read()  # 读取整个文件内容为一个长字符串
        return conversations
class ChatBot:
    def __init__(self,ID):
        self.ID=str(ID)
        self.API_KEY = "vRyL4Nfqxp8MN3W5kIgyKEDV"
        self.SECRET_KEY = "EwRWwW7V271mY0wE3H0TS2AVHCiZkk27"
    def get_access_token(self):
        """
        使用 API Key，Secret Key 获取access_token，替换下列示例中的应用API Key、应用Secret Key
        """

        url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}"
        final_url = url.format(self.API_KEY, self.SECRET_KEY)
        payload = json.dumps("")
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        response = requests.request("POST", final_url, headers=headers, data=payload)
        return response.json().get("access_token")


    def chat(self,question):
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-tiny-8k?access_token=" + self.get_access_token()
        #读取历史记录
        history_data=File.import_history("data/"+self.ID+".txt")
        # 使用json.loads将字符串转换为Python字典
        try:
            history_data_dict = json.loads(history_data+']')
        except:
            os.remove("data/" + self.ID + ".txt")
            return "服务器繁忙"
        new_user_message = {
            "role": "user",
            "content": question
        }
        # 将新的用户消息添加到列表中
        history_data_dict.append(new_user_message)
        payload = json.dumps({
            "messages":
                history_data_dict # 直接添加转换后的Python字典
        })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        if response.status_code == 200:
            # 解析JSON响应为Python字典
            # return response
            try:
                data = response.json()
                # 访问并打印result字段的值
                File.save_conversation(question,"data/"+self.ID+".txt","user")
                File.save_conversation(data["result"], "data/"+self.ID+".txt", "assistant")
                return data["result"]
            except:
                os.remove("data/" + self.ID + ".txt")
                return "服务器繁忙"
        else:
            print(f"请求失败，状态码: {response.status_code}")
            # 如果需要，可以打印出完整的响应内容
            File.save_conversation(question, "data/" + self.ID + ".txt", "user")
            File.save_conversation("", "data/" + self.ID + ".txt", "assistant")
            #print(response.text)
            return "请求失败"




